/**
 * 批量替换项目中的console调用为logger调用的脚本
 */

const fs = require('fs')
const path = require('path')
const glob = require('glob')

// 需要处理的文件模式
const patterns = [
  'src/**/*.vue',
  'src/**/*.ts',
  'src/**/*.js'
]

// 排除的文件
const excludePatterns = [
  'src/utils/logger.ts',
  'src/api/client.ts',
  'src/stores/cart.ts',
  'src/stores/auth.ts',
  'src/views/cart/Cart.vue',
  'src/views/home/Home.vue',
  'src/views/admin/OrderManage.vue',
  'src/views/admin/Dashboard.vue',
  'src/views/order/Checkout.vue'
]

// console调用的映射
const consoleMapping = {
  'console.log': 'logger.info',
  'console.info': 'logger.info',
  'console.warn': 'logger.warn',
  'console.error': 'logger.error',
  'console.debug': 'logger.debug'
}

// 获取所有需要处理的文件
function getAllFiles() {
  const files = []
  patterns.forEach(pattern => {
    const matches = glob.sync(pattern, { cwd: process.cwd() })
    files.push(...matches)
  })
  
  // 过滤掉排除的文件
  return files.filter(file => !excludePatterns.includes(file))
}

// 处理单个文件
function processFile(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf8')
    let modified = false
    let needsLoggerImport = false
    
    // 检查是否需要添加logger导入
    const hasConsoleCall = Object.keys(consoleMapping).some(consoleMethod => 
      content.includes(consoleMethod)
    )
    
    if (!hasConsoleCall) {
      return false
    }
    
    // 检查是否已经导入了logger
    const hasLoggerImport = content.includes('from \'@/utils/logger\'')
    
    if (!hasLoggerImport) {
      needsLoggerImport = true
    }
    
    // 替换console调用
    Object.entries(consoleMapping).forEach(([consoleMethod, loggerMethod]) => {
      const regex = new RegExp(`\\b${consoleMethod.replace('.', '\\.')}\\b`, 'g')
      if (content.match(regex)) {
        content = content.replace(regex, loggerMethod)
        modified = true
      }
    })
    
    // 添加logger导入
    if (needsLoggerImport && modified) {
      // 对于Vue文件
      if (filePath.endsWith('.vue')) {
        // 在script setup标签后添加导入
        const scriptSetupMatch = content.match(/<script setup lang="ts">\s*\n/)
        if (scriptSetupMatch) {
          const insertPos = scriptSetupMatch.index + scriptSetupMatch[0].length
          const imports = content.substring(0, insertPos)
          const rest = content.substring(insertPos)
          
          // 检查是否已有其他导入
          const hasOtherImports = rest.match(/^import .+ from .+$/m)
          const loggerImport = hasOtherImports 
            ? "import { createLogger } from '@/utils/logger'\n"
            : "import { createLogger } from '@/utils/logger'\n\n"
          
          content = imports + loggerImport + rest
          
          // 添加logger实例创建
          const componentNameMatch = filePath.match(/([^/]+)\.vue$/)
          const componentName = componentNameMatch ? componentNameMatch[1] : 'Component'
          const loggerInstance = `const logger = createLogger('${componentName}')\n\n`
          
          // 在第一个const/let/var声明前添加logger实例
          const firstVarMatch = rest.match(/^(const|let|var) /m)
          if (firstVarMatch) {
            const varPos = content.indexOf(firstVarMatch[0], insertPos + loggerImport.length)
            content = content.substring(0, varPos) + loggerInstance + content.substring(varPos)
          }
        }
      }
      // 对于TS文件
      else if (filePath.endsWith('.ts')) {
        // 在第一个import后添加logger导入
        const importMatch = content.match(/^import .+$/m)
        if (importMatch) {
          const insertPos = importMatch.index + importMatch[0].length + 1
          content = content.substring(0, insertPos) + 
                   "import { createLogger } from '@/utils/logger'\n" +
                   content.substring(insertPos)
          
          // 添加logger实例
          const fileNameMatch = filePath.match(/([^/]+)\.ts$/)
          const fileName = fileNameMatch ? fileNameMatch[1] : 'Module'
          const loggerInstance = `\nconst logger = createLogger('${fileName}')\n`
          
          content = content.substring(0, insertPos + "import { createLogger } from '@/utils/logger'\n".length) +
                   loggerInstance +
                   content.substring(insertPos + "import { createLogger } from '@/utils/logger'\n".length)
        }
      }
    }
    
    if (modified) {
      fs.writeFileSync(filePath, content, 'utf8')
      console.log(`✅ 已处理: ${filePath}`)
      return true
    }
    
    return false
  } catch (error) {
    console.error(`❌ 处理文件失败 ${filePath}:`, error.message)
    return false
  }
}

// 主函数
function main() {
  console.log('🚀 开始批量替换console调用...')
  
  const files = getAllFiles()
  console.log(`📁 找到 ${files.length} 个文件需要检查`)
  
  let processedCount = 0
  
  files.forEach(file => {
    if (processFile(file)) {
      processedCount++
    }
  })
  
  console.log(`\n✨ 完成! 共处理了 ${processedCount} 个文件`)
  console.log('\n📝 请手动检查以下内容:')
  console.log('1. 确认logger实例名称是否合适')
  console.log('2. 确认导入语句位置是否正确')
  console.log('3. 运行项目检查是否有编译错误')
}

if (require.main === module) {
  main()
}

module.exports = { processFile, getAllFiles }